<template>
  <view class="page-container min-h-screen flex flex-col bg-gray-100">
    <!-- 固定的顶部区域 -->
    <view class="fixed-header left-0 right-0 top-0 z-10">
      <!-- 顶部导航 -->
      <S1Header title="存单管理" :on-back="goBack" />

      <!-- 搜索框 -->
      <view class="search-box border-b border-gray-200 bg-white px-4 py-2">
        <view
          class="mx-auto h-[37px] w-[330px] flex items-center border border-[#e4eaf2] rounded-[18px] bg-[#f5f7fa] px-3"
        >
          <text class="icon-search mr-2 text-gray-400" @tap="handleSearch">
            🔍
          </text>
          <input
            v-model="searchKeyword" class="flex-1 bg-transparent text-sm" type="text" placeholder="搜索买家名称或单号"
            placeholder-class="text-gray-400" confirm-type="search" @confirm="handleSearch"
          >
        </view>
      </view>
    </view>

    <!-- 占位元素，高度等于固定头部的高度 -->
    <view class="header-placeholder" :style="{ height: `${headerHeight}px` }" />

    <!-- 订单列表 -->
    <scroll-view scroll-y class="order-list flex-1 bg-gray-100 pb-24 pt-2">
      <!-- 订单项 -->
      <view v-for="item in orderList" :key="item.id" class="mx-3 mb-3 overflow-hidden rounded-lg bg-white shadow-sm">
        <!-- 顶部区域: 订单信息区 -->
        <view class="px-3 pb-1 pt-2">
          <view class="mb-1 flex justify-between">
            <text class="text-sm text-green-500 font-medium">
              #{{ item.id }}
            </text>
            <text class="text-xs text-gray-400">
              {{ item.time }} 开单人：{{ item.user?.name || '未知' }}
            </text>
          </view>
        </view>

        <!-- 内容和按钮并排区域 -->
        <view class="flex px-3 pb-2">
          <!-- 左侧内容区（带红边框） -->
          <view class="mr-2 flex-1 border border-red-500 rounded p-1.5">
            <view class="flex">
              <!-- 复选框 -->
              <checkbox
                class="mr-2 scale-80 transform" :checked="selectedOrders.includes(item.id)"
                color="#07c160" @tap="toggleSelect(item.id)"
              />

              <!-- 内容区 -->
              <view class="flex-1">
                <view class="mb-1 flex justify-between">
                  <text class="font-medium">
                    {{ item.name }}({{ item.sort }})
                  </text>
                  <text class="text-sm text-green-500">
                    应收：<text class="text-red-500">
                      {{ item.total_price }}
                    </text>
                  </text>
                </view>
                <view class="flex justify-between">
                  <text class="block truncate pr-2 text-xs text-gray-400">
                    {{ formatGoodsList(item.order_car) }}
                  </text>
                  <text class="whitespace-nowrap text-xs text-gray-400">
                    共{{ item.order_car?.length || 0 }}种商品
                  </text>
                </view>
              </view>
            </view>
          </view>

          <!-- 右侧按钮区 -->
          <view class="flex flex-col justify-center">
            <button
              class="mb-1.5 w-14 rounded-sm bg-orange-500 px-0 py-1 text-xs text-white"
              @tap="handleTakeOrder(item.id)"
            >
              取单
            </button>
            <button
              class="w-14 rounded-sm bg-green-500 px-0 py-1 text-xs text-white"
              @tap="navigateToSettlement(item.id)"
            >
              结算
            </button>
          </view>
        </view>
      </view>

      <!-- 加载状态 -->
      <view v-if="orderList.length === 0" class="load-tip py-3 text-center text-xs text-gray-400">
        暂无数据
      </view>
      <view v-else class="load-tip py-3 text-center text-xs text-gray-400">
        已加载全部数据
      </view>
    </scroll-view>

    <!-- 底部工具栏 -->
    <view
      class="footer-bar fixed bottom-0 left-0 right-0 h-[110rpx] flex items-center justify-between border-t border-t-[#eee] bg-white"
    >
      <view class="ml-4 flex items-center">
        <checkbox
          class="scale-80 transform" :checked="selectedOrders.length > 0" color="#07c160"
          @tap="toggleSelectAll"
        />
        <text class="ml-2 text-sm">
          已勾选
        </text>

        <view class="ml-2">
          <text class="block text-xs">
            {{ selectedOrders.length }}个买家
          </text>
          <text class="block text-xs">
            {{ getSelectedGoodsCount() }}个货品
          </text>
        </view>
      </view>

      <view class="mr-3 flex">
        <button
          class="mr-[10rpx] h-[80rpx] rounded-[8rpx] border-none bg-orange-500 px-[30rpx] text-sm text-white leading-[80rpx]"
          @tap="handleBatchTakeOrder"
        >
          批量取单
        </button>
        <button
          class="mr-[20rpx] h-[80rpx] rounded-[8rpx] border-none bg-green-500 px-[30rpx] text-sm text-white leading-[80rpx]"
          @tap="handleBatchEditPrice"
        >
          批量改价
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { getMaijiaCarqudan, guadantocar } from '@/api/order';
import S1Header from '@/components/S1Header.vue';
import { useUserStore } from '@/store';

// 定义接口类型
interface OrderCarItem {
  goods_name: string;
  num: number;
  weight: number;
  price: number;
  mini_type: string;
}

interface OrderItem {
  id: number;
  name: string;
  time: string;
  total_price: number;
  order_car?: OrderCarItem[];
  sort: string | number; // 同时支持string和number类型
  user?: {
    name: string;
  };
  maijia_id?: number; // 添加maijia_id字段
}

// 获取用户store
const userStore = useUserStore();

// 搜索关键词
const searchKeyword = ref('');

// 防抖定时器
let searchDebounce: ReturnType<typeof setTimeout> | null = null;

// 订单列表数据
const orderList = ref<OrderItem[]>([]);

// 已选择的订单ID
const selectedOrders = ref<number[]>([]);

// 头部高度
const headerHeight = ref(180); // 默认高度，单位px

// 监听搜索关键词变化
watch(searchKeyword, (newVal) => {
  // 清除之前的定时器
  if (searchDebounce) clearTimeout(searchDebounce);

  // 设置新的定时器，延迟300ms执行搜索
  searchDebounce = setTimeout(() => {
    getMaijiaCarqudanList();
  }, 300);
});

// 处理搜索
function handleSearch(): void {
  // 实现搜索逻辑
  console.log('搜索关键词:', searchKeyword.value);
  // 根据关键词搜索订单
  getMaijiaCarqudanList();
}

// 获取存单列表
const getMaijiaCarqudanList = async (): Promise<void> => {
  try {
    // 从userStore获取user_id作为maijia_id传参
    const maijia_id = Number(userStore.user_id);
    const res = await getMaijiaCarqudan({
      maijia_id,
      keywords: searchKeyword.value,
    });

    if (res.code === 200 && res.data) {
      // 使用类型断言转换数据
      orderList.value = res.data as unknown as OrderItem[];
    }
    else {
      console.error('获取存单列表失败:', res.msg);
      uni.showToast({
        title: res.msg || '获取存单列表失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('获取存单列表异常:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none',
    });
  }
};

// 格式化商品列表展示
function formatGoodsList(goodsList: OrderCarItem[] | undefined): string {
  if (!goodsList || goodsList.length === 0) return '无商品';

  return goodsList.slice(0, 2).map((item) => {
    const goodsName = item.goods_name || '';
    const num = item.num || 0;
    const weight = item.weight || 0;

    if (item.mini_type === '公斤') {
      return `${goodsName} ${weight}×${item.price}`;
    }
    else {
      return `${goodsName} ${num}×${item.price}`;
    }
  }).join(' ');
}

// 切换选择状态
function toggleSelect(id: number): void {
  const index = selectedOrders.value.indexOf(id);
  if (index > -1) {
    selectedOrders.value.splice(index, 1);
  }
  else {
    selectedOrders.value.push(id);
  }
}

// 切换全选状态
function toggleSelectAll(): void {
  if (selectedOrders.value.length > 0) {
    selectedOrders.value = [];
  }
  else {
    selectedOrders.value = orderList.value.map((item: OrderItem) => item.id);
  }
}

// 获取已选择的商品总数
function getSelectedGoodsCount(): number {
  let count = 0;
  selectedOrders.value.forEach((id: number) => {
    const order = orderList.value.find((item: OrderItem) => item.id === id);
    if (order && order.order_car) {
      count += order.order_car.length;
    }
  });
  return count;
}

// 处理取单操作
async function handleTakeOrder(id: number): Promise<void> {
  try {
    const result = await guadantocar({
      car_id: id,
    });

    if (result.code === 200) {
      uni.showToast({
        title: '取单成功',
        icon: 'success',
      });

      // 取单成功后，返回购物车页面并传递id
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/cart/index?id=${id}`,
        });
      }, 1500);
    }
    else {
      uni.showToast({
        title: result.msg || '取单失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('取单异常:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none',
    });
  }
}

// 处理批量取单
async function handleBatchTakeOrder(): Promise<void> {
  if (selectedOrders.value.length === 0) {
    uni.showToast({
      title: '请先选择要取单的订单',
      icon: 'none',
    });
    return;
  }

  uni.showModal({
    title: '批量取单',
    content: `确定要取单选中的${selectedOrders.value.length}个订单吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          // 批量取单使用car_ids参数
          const result = await guadantocar({
            car_ids: selectedOrders.value,
          });

          if (result.code === 200) {
            uni.showToast({
              title: '批量取单成功',
              icon: 'success',
            });

            // 批量取单成功后，返回购物车页面，不传递特定maijia_id
            setTimeout(() => {
              uni.navigateTo({
                url: '/pages/cart/index',
              });
            }, 1500);
          }
          else {
            uni.showToast({
              title: result.msg || '批量取单失败',
              icon: 'none',
            });
          }
        }
        catch (error) {
          console.error('批量取单异常:', error);
          uni.showToast({
            title: '网络异常，请稍后重试',
            icon: 'none',
          });
        }
      }
    },
  });
}

// 处理批量改价
function handleBatchEditPrice(): void {
  if (selectedOrders.value.length === 0) {
    uni.showToast({
      title: '请先选择要改价的订单',
      icon: 'none',
    });
    return;
  }

  console.log('批量改价:', selectedOrders.value);
  uni.showToast({
    title: '批量改价功能开发中',
    icon: 'none',
  });
}

// 计算并设置头部高度
onMounted(() => {
  // 在真实DOM挂载后，获取头部高度
  uni.createSelectorQuery()
    .select('.fixed-header')
    .boundingClientRect((data) => {
      if (data && typeof data === 'object' && 'height' in data && typeof data.height === 'number') {
        headerHeight.value = data.height;
      }
    })
    .exec();

  // 调用获取列表函数
  getMaijiaCarqudanList();
});

// 页面显示时刷新列表
onShow(() => {
  // 每次页面显示时刷新数据
  getMaijiaCarqudanList();
});

// 返回上一页
function goBack(): void {
  uni.navigateBack();
}

// 跳转到收银页面
function navigateToSettlement(orderId: number): void {
  // 查找当前订单数据
  const currentOrder = orderList.value.find((item: OrderItem) => item.id === orderId);

  if (!currentOrder) {
    uni.showToast({
      title: '订单数据不存在',
      icon: 'none',
    });
    return;
  }

  // 准备结算数据
  const settlementData = {
    orderId: currentOrder.id,
    buyerName: currentOrder.name,
    orderItems: currentOrder.order_car || [],
    yingshou: currentOrder.total_price,
    heji: currentOrder.total_price,
    shishou: currentOrder.total_price,
    cash_num: currentOrder.total_price,
    wepay_num: 0,
    alipay_num: 0,
    union_num: 0,
    other_num: 0,
  };

  // 将数据保存到本地存储，避免URL参数长度限制和解析问题
  uni.setStorageSync('settlementData', settlementData);

  // 跳转到结算页面，不携带参数
  uni.navigateTo({
    url: `/pages/common/settlement/index`,
  });
}
</script>

<style scoped>
.fixed-header {
  position: fixed;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.header-placeholder {
  width: 100%;
}
</style>
